<?php

namespace Biz\model;

use Biz\tools\ShopArea;
use Doraemon\pockets\datebase\BaseDbModel;

class ShippingTemplAttr extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_shop';

    const _DATABASE_ = 'shop';

    const _TABLE_NAME = 'shop_shipping_templ_attr';

    const _SUB_TABLE = false;

    const STATUS_PASSED = 1;//正常
    const STATUS_DELETE = 9;//删除

    const TYPE_FREE = 1;
    const TYPE_NOFREE = 2;


    public static function addAttr($data)
    {
        self::insert($data);
        return self::id();
    }

    public static function addAttrs($data)
    {
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            throw new \Exception('添加运费模板错误');
        }
        return true;
    }

    public static function updateAttr($data, $where)
    {
        return self::update($data, $where)->rowCount();
    }

    public static function getByTemplId($templId, $status = null, $order = [])
    {
        $where = ['templ_id' => $templId];
        if (!is_null($status)) {
            $where['status'] = $status;
        }
        if ($order) {
            $where['ORDER'] = $order;
        }
        return self::select('*', $where);
    }

    public static function getAttrsByTid($tempIds)
    {
        $attrInfos = self::select("*", [
            'templ_id' => $tempIds,
            'status' => self::STATUS_PASSED,
        ]);

        $attrInfos = array_map(function ($attrInfo) {
            $attrInfo['area_str'] = ShopArea::locationId2String($attrInfo['area']);
            return $attrInfo;
        }, $attrInfos);

        $returnRst = [];
        foreach ($attrInfos as $attrInfo) {
            $returnRst[$attrInfo['templ_id']][] = $attrInfo;
        }

        return $returnRst;

    }

    public static function getDefaultPrice($templ_id)
    {
        return self::get('base_price', [
            'templ_id' => $templ_id,
            'is_default' => 1,
            'status' => self::STATUS_PASSED
        ]);
    }
}